﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BattleThis.Core;
using System.Web.WebPages.Html;
using System.Web.Mvc;
using BattleThis.Controllers;
using BattleThis.Core.Battle;


namespace BattleThis.Helpers
{
	public static class UrlHelperExtension
	{
		
		public static string SrcFor( this UrlHelper url, Experience experiance )
		{
			var imageFilePattern = "RankLevel{0}";
			var displayLevel = experiance.Level > 2  ? 3:experiance.Level;

			return SrcFor(url, string.Format( imageFilePattern, experiance.Level ));
			
		}

		public static string SrcFor( this UrlHelper url, Unit unit )
		{
			return url.Action( BattleThis.Controllers.SvgController.RenderUnit, "Svg", new { UnitId = unit.Id } );
		}

		public static string SrcFor( this UrlHelper url, string contentName )
		{
			var contentPath = string.Format( "~/Content/themes/base/images/fields/{0}{1}", contentName, Definitions.ImageExtension );
			return VirtualPathUtility.ToAbsolute( contentPath );
			
		}

		public static string Command( this UrlHelper context, Field field )
		{
			var gameContext = context.RequestContext.HttpContext.GetGameContext();

			if( !gameContext.Selection.IsNone() )
			{
				return UnitCommand( context, field );
			}
			else
			{
				return SelectCommand( context, field );
			}
		}

		public static string UnitCommand( UrlHelper context, Field field )
		{
			var gameContext = context.RequestContext.HttpContext.GetGameContext();

			if( gameContext.Selection.IsInMoveRange( field ) && field.Unit.IsEmpty() )
			{
				return MoveCommand( context, field, gameContext );
			}
			else if( gameContext.Selection.IsInAttackRange( field ) && !field.Unit.IsEmpty() )
			{
				return AttackCommand( context, field );
			}
			else
			{
				return ResetCommand( context );
			}
		}

		public static string SelectCommand( UrlHelper context, Field field )
		{
			if( field.Unit.IsEmpty() )
			{
				return "#";
			}
			else
			{
				return context.Action( GameController.SelectAction,
										GameController.Info.ControllerName,
											new { unitId = field.Unit.Id } );
			}
		}

		private static string ResetCommand( UrlHelper context )
		{
			return context.Action( GameController.IndexAction, 
									GameController.Info.ControllerName );
		}

		private static string AttackCommand( UrlHelper context, Field field )
		{
			return context.Action( BattleController.AttackCommand, 
									BattleController.Info.ControllerName,
										new { targetId = field.Unit.Id } );
		}

		private static string MoveCommand( UrlHelper context, Field field, GameContext gameContext )
		{
			var currentUnit = gameContext.Selection.Unit;

			return context.Action( GameController.MoveAction, 
									GameController.Info.ControllerName, new
										{
										unitId = currentUnit.Id,
										column = field.Position.Column,
										row = field.Position.Row
										} );
		}

	}
}